import 'package:dio/dio.dart';
import 'package:easy_video/internal/middleware/app_middleware.dart';
import 'package:get/get.dart' as G;
import 'package:bot_toast/bot_toast.dart';

import '../controller/app_controller.dart';
import 'middleware/http_limiting_middleware.dart';

class HttpClient {
  static final BaseOptions baseOptions = BaseOptions(
    // baseUrl: "http://127.0.0.1:9991",
    baseUrl: "https://api.xcd.icu",
    connectTimeout: Duration(seconds: 5),
    receiveTimeout: Duration(seconds: 5),
  );

  final Dio dio = Dio(baseOptions);

  HttpClient() {
    //请求拦截器

    dio.interceptors.add(AppMiddleware());

    dio.interceptors.add(HttpLimitingMiddleware());

    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handle) {
          if (AppController().isLogin) {
            request.headers["Token"] = AppController().token;
          }
          return handle.next(request);
        },
        onResponse: (response, handle) {
          var code = response.data?["code"] ?? 0;
          if (code == 0) {
            BotToast.showSimpleNotification(
              title: response.data?["message"] ?? "系统错误",
            );
            return;
          }
          return handle.next(response);
        },
        onError: (DioException error, handler) {
          switch (error.response?.statusCode) {
            case 401:
              G.Get.toNamed('/login');
              return;
            case 404:
              print({
                "未找到接口:",
                error.requestOptions.uri,
              });
              BotToast.showSimpleNotification(
                title: "系统错误,未找到接口地址",
              );
              return;
            case 413:
              BotToast.showSimpleNotification(
                title: "系统错误,上传内容大小太大",
              );
              return;
            default:
              return handler.next(error);
          }
        },
      ),
    );
  }

  Future<Response<T>> get<T>(String path,
      {Map<String, dynamic>? queryParameters, Options? options}) async {
    return await dio.get<T>(
      path,
      queryParameters: queryParameters,
      options: options,
    );
  }

  Future<Response<T>> post<T>(String path, {data, Options? options}) async {
    return await dio.post<T>(path, data: data, options: options);
  }
}
